<template>
	<view class="wrap-chart">
		<!-- <u-input :value="JSON.stringify(chartData)" /> -->
		<view class="block-title">
			<u-image src="/static/home/icon_env.png" width="38" height="38" />
			<view class="txt">{{title}}</view>
		</view>

		<view class="condition-block">
			<view class="left">
				<view :class="['item','first-item',{'active':activeIndex === 0}]" @click="switchCondition(0)">时
				</view>
				<view :class="['item','item-center',{'active':activeIndex === 1}]" @click="switchCondition(1)">日
				</view>
				<view :class="['item','item-center',{'active':activeIndex === 2}]" @click="switchCondition(2)">月
				</view>
				<view :class="['item','last-item',{'active':activeIndex === 3}]" @click="switchCondition(3)">年
				</view>
			</view>
			<picker mode="date" :fields="dateMode" :value="currentDate" @change="changeDate" v-show='dateMode'>
				<view class="right">
					<view class="uni-input">{{currentDate}}</view>
					<u-icon name="arrow-down-fill" />
				</view>
			</picker>
		</view>

		<view class="chart-box">
			<qiun-data-charts :type="chartType" :chartData="chartData" :disableScroll="false" :opts="opts"
				:tapLegend="true" :ontouch="true" :onmovetip="true" tooltipFormat="myTooltipFormat" v-show="loadFinish">
			</qiun-data-charts>
			<view v-show="!loadFinish" class="loading">
				<u-loading mode="circle" size="50"></u-loading>
				<view class="txt">加载中</view>
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		props: {
			stationId: null,
			deviceId: null,
			title: {
				type: String,
				default: '功率|电量'
			}
		},
		data() {
			return {
				loadFinish: false,
				activeIndex: 0,
				today: null,
				currentDate: null,
				dateMode: 'day',
				chartData: {
					categories: [],
					series: [{
						data: []
					}]
				},
				chartType: 'line',
				opts: {
					"chartIndex": 0, //自定义参数，用来控制tooltip
					"type": 'line',
					"canvasId": "",
					"canvas2d": false,
					"background": "none",
					"animation": true,
					"timing": "easeOut",
					"duration": 1000,
					"padding": [10, 0, 0, 0],
					"rotate": false,
					"errorReload": true,
					"fontSize": 10,
					"fontColor": "#999",
					"enableScroll": false,
					"touchMoveLimit": 60,
					"enableMarkLine": false,
					"dataLabel": false,
					"dataPointShape": false,
					"dataPointShapeType": "solid",
					"tapLegend": false,
					"loadingType": 3,
					xAxis: {
						"disabled": false,
						"axisLine": true,
						"axisLineColor": "#999",
						"calibration": false,
						"fontColor": "#999",
						"fontSize": 10,
						"rotateLabel": false,
						"itemCount": 4,
						"boundaryGap": "justify",
						"disableGrid": true,
						"gridColor": "#CCCCCC",
						"gridType": "solid",
						"dashLength": 4,
						"gridEval": 1,
						"scrollShow": false,
						"scrollAlign": "left",
						"scrollColor": "#A6A6A6",
						"scrollBackgroundColor": "#EFEBEF",
						"format": "xTimeFormat"
					},
					yAxis: {
						"disabled": false,
						"disableGrid": false,
						"splitNumber": 4,
						"gridType": "dash",
						"dashLength": 1,
						"gridColor": "#E6E6E6",
						"padding": 10,
						"showTitle": true,
						"data": [{
							"type": "value",
							"position": "left",
							"disabled": false,
							"axisLine": true,
							"axisLineColor": "#CCCCCC",
							"calibration": false,
							"fontColor": "#666666",
							"fontSize": 13,
							"textAlign": "right",
							"title": "MWh",
							"titleFontSize": 15,
							"titleOffsetY": -5,
							"titleOffsetX": -5,
							"titleFontColor": "#000",
							"min": null,
							"max": null,
							"tofix": 1,
							"unit": "",
							"format": ""
						}]
					},
					"legend": {
						"show": true,
						"position": "top",
						"float": "center",
						"padding": 5,
						"margin": 5,
						"backgroundColor": "rgba(0,0,0,0)",
						"borderColor": "rgba(0,0,0,0)",
						"borderWidth": 0,
						"fontSize": 13,
						"fontColor": "#666666",
						"lineHeight": 11,
						"hiddenColor": "#CECECE",
						"itemGap": 10
					},
					"extra": {
						"line": {
							"type": "curve",
							"width": 2
						},
						"column": {
							"seriesGap": 4
						},
						"tooltip": {
							"showBox": true,
							"showArrow": true,
							"showCategory": false,
							"borderWidth": 0,
							"borderRadius": 0,
							"borderColor": "#000000",
							"borderOpacity": 0.7,
							"bgColor": "#000000",
							"bgOpacity": 0.7,
							"gridType": "solid",
							"dashLength": 4,
							"gridColor": "#CCCCCC",
							"fontColor": "#FFFFFF",
							"splitLine": true,
							"horizentalLine": false,
							"xAxisLabel": false,
							"yAxisLabel": false,
							"labelBgColor": "#FFFFFF",
							"labelBgOpacity": 0.7,
							"labelFontColor": "#666666"
						},
						"markLine": {
							"type": "solid",
							"dashLength": 4,
							"data": []
						}
					}
				}
			}
		},
		beforeMount() {
			this.currentDate = this.$u.timeFormat(new Date(), 'yyyy-mm-dd')
			this.today = this.currentDate
		},
		methods: {
			switchCondition(index) {
				if (this.activeIndex === index) return
				this.activeIndex = index
				this.opts.chartIndex = index
				if (index === 0) {
					this.dateMode = 'day'
					this.currentDate = this.today
				} else if (index === 1) {
					this.dateMode = 'month'
					this.currentDate = this.today.substring(0, 7)
				} else if (index === 2) {
					this.dateMode = 'year'
					this.currentDate = this.today.substring(0, 4)
				} else if (index === 3) {
					this.dateMode = null
					this.currentDate = ""
				}
				this.loadChartInfo()
			},
			changeDate(e) {
				this.currentDate = e.target.value
				this.loadChartInfo()
			},
			loadChartInfo() {
				this.loadFinish = false
				if (this.deviceId !== null && this.deviceId !== undefined) { //查询某个设备
					this.$u.api.getDeviceChartInfo({
						deviceId: this.deviceId,
						date: this.currentDate
					}).then(res => {
						this.handleData(res, false)
					})
				} else if (this.stationId !== null && this.stationId !== undefined) { //查某个站点
					this.$u.api.getStationChartInfo({
						stationId: this.stationId,
						date: this.currentDate
					}).then(res => {
						this.handleData(res, false)
					})
				} else { //查所有
					// console.error('loadChartInfo=', this.currentDate)
					this.$u.api.getChartInfo({
						date: this.currentDate
					}).then(res => {
						this.handleData(res, true)
					})
				}
			},
			handleData(res, isAll) {
				if (res.error_code !== 0) return
				let y_max = 1
				if (this.activeIndex === 0) {
					//功率
					let ssgl = res.data.ssgl
					//判断是否有大于1000的数值
					let hasGreatThan1K = ssgl.ydata.filter(item => item && item !== '-').some(item => parseFloat(item) >
						1000)
					this.chartType = 'line'
					this.opts.type = 'line'
					this.opts.xAxis.format = 'xTimeFormat'
					this.opts.yAxis.data[0].title = 'KW'
					this.opts.yAxis.data[0].unit = hasGreatThan1K ? 'K' : '' //单位
					let ydata_ssgl = []
					ssgl.ydata.forEach((item, index) => {
						if (item && item !== '-') {
							let val = hasGreatThan1K ? (parseFloat(item) / 1000) : parseFloat(item)
							if (val > y_max) y_max = val
							ydata_ssgl.push(val < 0 ? 0 : val)
						} else {
							ydata_ssgl.push(null)
						}
					})
					this.chartData.categories = ssgl.xdata
					this.chartData.series = [{
						name: '功率',
						data: ydata_ssgl,
						color: '#91CB74'
					}]
				} else {
					this.chartType = 'column'
					this.opts.type = 'column'
					let fdl = res.data.fdl
					//判断是否有大于1000的数值
					let hasGreatThan1K = fdl.ydata.filter(item => item && item !== '-').some(item => parseFloat(item) >
						1000)
					console.log('hasGreatThan1K=', hasGreatThan1K)
					this.opts.yAxis.data[0].title = this.activeIndex === 1 ? 'KWh' : 'MWh'
					//如果是日，并且数据有大于1000的，并且不是设备
					this.opts.yAxis.data[0].unit = hasGreatThan1K ? 'K' : ''

					let ydata = []
					fdl.ydata.forEach((item, index) => {
						let val = null
						if (item && item !== '-') {
							val = hasGreatThan1K ? (parseFloat(item) / 1000) : parseFloat(item)
							console.log('y_max=', y_max, 'val=', val)
							if (val > y_max) y_max = val
							val = val < 0 ? 0 : val
						}
						ydata.push(val)
					})
					let xdata = []
					//处理日期
					if (this.activeIndex === 1) {
						this.opts.xAxis.format = 'xDayFormat'
						xdata = fdl.xdata.map(item => item.substring(8, 10))
					} else if (this.activeIndex === 2) {
						this.opts.xAxis.format = ''
						xdata = fdl.xdata.map(item => item.substring(5))
					} else if (this.activeIndex === 3) {
						xdata = fdl.xdata
					}

					this.chartData.categories = xdata
					//当“年”只有一个column的时候，需要特殊处理一下，不显示tooltip
					let onlyOneYearData = ''
					if (this.activeIndex === 3 && ydata.length === 1) {
						onlyOneYearData = hasGreatThan1K ? (ydata[0] * 1000).toFixed(2) : ydata[0].toFixed(2)
					}
					this.chartData.series = [{
						name: `发电量${onlyOneYearData}`,
						data: ydata,
						color: '#91CB74'
					}]
				}
				this.opts.yAxis.data[0].min = 0
				this.opts.yAxis.data[0].max = y_max * 1.1 //设置y轴最大值
				console.log(y_max)
				this.loadFinish = true
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wrap-chart {
		// height: 600upx;
		padding: 28upx 32upx;
		// background: red;

		.block-title {
			display: flex;
			align-items: center;

			.txt {
				margin-left: 10upx;
				font-weight: 400;
				font-size: 28upx;
				color: #999;
			}
		}

		.condition-block {
			margin: 34upx 0;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.left {
				width: 330upx;
				display: flex;
				background-color: #EBF4FF;
				height: 60upx;
				color: #333;
				font-size: 28upx;
				border-radius: 35upx;
				border: 1upx solid #378FFA;

				.first-item {
					border-top-left-radius: 36upx;
					border-bottom-left-radius: 36upx;
				}

				.item-center {
					border-left: 1upx solid #378FFA;
				}

				.item {
					line-height: 62upx;
					width: 110upx;
					text-align: center;
				}

				.last-item {
					border-top-right-radius: 36upx;
					border-bottom-right-radius: 36upx;
					border-left: 1upx solid #378FFA;
				}

				.active {
					background-color: #378FFA;
					color: #fff;
				}
			}

			.right {
				width: 198upx;
				height: 60upx;
				border-radius: 40upx;
				border: 1px solid #378FFA;
				text-align: center;
				line-height: 60upx;
				font-size: 24upx;
				font-weight: 400;
				color: #378FFA;
				display: flex;
				justify-content: space-around;
				padding: 0 15upx;
			}
		}

		.chart-box {
			width: 100%;
			min-height: 455upx;
			display: flex;
			align-items: center;
			justify-content: center;

			// background: green;
			.loading {
				text-align: center;

				.txt {
					margin-top: 30upx;
					font-size: 24upx;
				}
			}
		}
	}
</style>
